<template>
  <uni-popup ref="popup" type="bottom" @change="change" safeArea backgroundColor="#fff" :maskClick="false"
    class="i-addressPicker">
    <view class="picker">
      <view class="title">
        <text @click="close">取消</text>
        <text class="confirm" @click="confirm">确认</text>
      </view>
      <picker-view :value="selectData" @change="bindChange" class="picker-view" indicator-style="height: 34px;">
        <picker-view-column>
          <view class="item" v-for="item in list.province" :key="item.id">{{
            item.name
          }}</view>
        </picker-view-column>
        <picker-view-column v-if="props.level >= '2'">
          <view class="item" v-for="item in list.city" :key="item.id">{{
            item.name
          }}</view>
        </picker-view-column>
        <picker-view-column v-if="props.level >= '3'">
          <view class="item" v-for="item in list.county" :key="item.id">{{
            item.name
          }}</view>
        </picker-view-column>
      </picker-view>
    </view>
  </uni-popup>
</template>

<script lang="ts" setup>
import { baseListByParent } from "../../api/index";
import { defineProps, defineEmits, ref, reactive, onMounted, watch } from "vue";
const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  confirm_title: {
    type: String,
    default: "",
  },
  modelValue: {
    type: Boolean,
    default: false,
  },
  diySlot: {
    type: Boolean,
    default: false,
  },
  level: {
    type: String,
    default: "3", // 1: 只显示一级，2: 省市，3: 省市区
  },
  defaultCode: {
    type: Array,
    default: [],
  },
});

const list = reactive<any>({
  province: [],
  city: [],
  county: [],
});

const selectData = ref([0, 0, 0]);
const emit = defineEmits(["confirm", "update:modelValue"]);
const popup = ref<any>(null);

const change = (e) => {
  if (!e.show) {
    emit("update:modelValue", false);
  }
};

const bindChange = (e: any) => {
  const val = e.detail.value;
  selectData.value.map((item, index) => {
    if (val[index] !== item) {
      switch (index) {
        case 0:
          if (props.level >= "2") {
            getCityList(list.province[val[index]].id);
          }
          break;
        case 1:
          if (props.level >= "3") {
            getCountyList(list.city[val[index]].id);
          }
          break;
        default:
          break;
      }
      return;
    }
  });
  selectData.value = val;
};

// 根据传入的 defaultCode 设置选中项的索引
const setDefaultValues = async () => {
  // 省份索引
  const provinceIndex = list.province.findIndex(
    (item) => item.id === props.defaultCode[0]
  );
  if (provinceIndex !== -1) {
    selectData.value[0] = provinceIndex;

    // 市索引
    if (props.defaultCode[1] && props.level >= "2") {
      // 如果省份变了，需要重新获取市列表
      const provinceId = String(props.defaultCode[0]);
      const { data: cities } = await baseListByParent(provinceId);
      list.city = cities;

      const cityIndex = list.city.findIndex(
        (item) => item.id === props.defaultCode[1]
      );
      if (cityIndex !== -1) {
        selectData.value[1] = cityIndex;

        // 区县索引
        if (props.defaultCode[2] && props.level >= "3") {
          // 如果市变了，需要重新获取区县列表
          const cityId = String(props.defaultCode[1]);
          const { data: counties } = await baseListByParent(cityId);
          list.county = counties;

          const countyIndex = list.county.findIndex(
            (item) => item.id === props.defaultCode[2]
          );
          if (countyIndex !== -1) {
            selectData.value[2] = countyIndex;
          }
        }
      }
    }
  }
};

const getProvinceList = async () => {
  const { data: province } = await baseListByParent("100000");
  list.province = province;

  if (props.level >= "2") {
    const { data: city } = await baseListByParent(province[0].id);
    list.city = city;

    if (props.level >= "3") {
      const { data: district } = await baseListByParent(city[0].id);
      list.county = district;
    }
  }

  // 处理 defaultCode
  if (props.defaultCode && props.defaultCode.length > 0) {
    setDefaultValues();
  }
};

const getCityList = async (parentId: string) => {
  const { data } = await baseListByParent(parentId);
  list.city = data;
  if (props.level >= "3") {
    getCountyList(data[0].id, true);
  }
};

const getCountyList = async (parentId: string, type?: boolean) => {
  !type &&
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });
  const { data } = await baseListByParent(parentId);
  list.county = data;
  !type && uni.hideLoading();
};

const close = () => {
  emit("update:modelValue", false);
};

const confirm = () => {
  const mapData = {
    province: "",
    city: "",
    county: "",
    address: "",
    provinceName: "",
    countyName: "",
    cityName: "",
  };

  const province = list.province[selectData.value[0]];
  mapData.province = province?.id || "";
  mapData.provinceName = province?.name;
  mapData.address = province?.name;

  if (props.level >= "2") {
    const city = list.city[selectData.value[1]];
    mapData.city = city?.id || "";
    mapData.cityName = city?.name;
    mapData.address += city?.name || "";
  }

  if (props.level >= "3") {
    const county = list.county[selectData.value[2]];
    mapData.county = county?.id || "";
    mapData.countyName = county?.name;
    mapData.address += county?.name || "";
  }
  emit("confirm", mapData);
  close();
};

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      popup.value.open();
    } else {
      popup.value.close();
    }
  }
);

watch(
  () => props.defaultCode,
  (val) => {
    console.log(val, 'vvvvvvvvvvv')
    if (val && val.length > 0) {
      setDefaultValues();
    } else {
      selectData.value = [0, 0, 0]
    }
  },
  { deep: true }
);

watch(
  () => props.level,
  () => {
    getProvinceList();
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.i-addressPicker {
  .picker {
    background-color: #fff;
    width: 100%;
    height: 480rpx;
    border-top: 1rpx solid #f3f4f5;
    border-radius: 16rpx 16rpx 0 0;
    padding-bottom: 40rpx;
    padding: 24rpx 0 0 0;

    .title {
      padding: 0 32rpx;
      @include flexRS;
      padding-bottom: 20rpx;
      border-bottom: 1rpx solid #f3f4f5;
      @include titlefont(32rpx);

      .confirm {
        color: #fb652e;
      }
    }

    .picker-view {
      height: 400rpx;
      margin-bottom: 80rpx;
    }

    .item {
      @include dfont;
      text-align: center;
      white-space: nowrap;
      line-height: 34px;
    }
  }
}
</style>
